var express = require('express');

var router = express.Router();

var UserEntity = require('../models/User').UserEntity;

var Result = require('../Result').Result;

var Code = require('../Result').Code;

router.post('/register',function (req,res,next) {
	var UserResult = new Result();
	var userName = req.body.userName;
	if(userName.length !== 11) {
		UserResult.errorCode = Code.ILLEGAL_ARGUMENT_ERROR_CODE;
		UserResult.errorMsg = '输入正确的电话号码';
		res.send(UserResult);
		return
	}
	var password = req.body.password;
	if(password.length < 7){
		UserResult.errorCode = Code.ILLEGAL_ARGUMENT_ERROR_CODE;
		UserResult.errorMsg = '输入正确的密码';
		res.send(UserResult);
		return;
	}
	UserEntity.findOne({userName:userName},'_id',function (err,user) {
		if(err){
			console.log(err);
			return;
		}
		if(user) {
			UserResult.errorCode = Code.ILLEGAL_ARGUMENT_ERROR_CODE;
			UserResult.errorMsg = '重复的用户名';
			res.send(UserResult);
			return
		}
		var registerUser = new UserEntity({userName:userName,password:password});

		registerUser.save(function (err,row) {
			if(err) {
				UserResult.errorCode = Code.SERVER_EXCEPTION_ERROR_CODE;
				UserResult.errorMsg = '服务器出错'
				return
			}
			UserResult.ok = 'ok'
			res.send(UserResult);
		})
	})
})

router.post('/login',function (req,res) {
	var user = req.body;
	console.log(user)
	UserEntity.findOne(user,function (err,doc) {
		console.log(doc)
		if(doc) {
			if(doc.isLogin) {
				res.send({'responseData':'您的账号已经登录',returnCode:1});
				return;
			}
			UserEntity.update(user,{$set:{isLogin:true}},function (err) {
				if(!err) {
					res.send({responseData:doc.userName,returnCode:0})
				}else{
					// res.send('faild')
				}
			})
		}else{
			res.send({user:"faild"})
		}
	})

})

router.post('/forget',function (req,res) {
	var user = req.body;
	UserEntity.findOne({userName:user.userName},function (err,doc) {
		if(doc) {
			UserEntity.update({userName:user.userName},{$set:{password:user.password}},function (err) {
				if(!err) {
					res.send('success')
				}
			})
		}
	})
})

router.post('/friendsList',function (req,res) {
	var data = req.body.userName;

	UserEntity.findOne({userName:data},function (err,doc) {
		if(!err) {
			res.send({friendsList:doc.friendList})
		}
	})
})

module.exports = router;